package com.avic.rong.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.mine.BindPhoneActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.api.login_register.UserLoginApi;
import com.avic.rong.api.login_register.WxLoginApi;
import com.avic.rong.api.mine.UpdateInterestApi;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.bean.login_register.LoginPhoneBean;
import com.avic.rong.bean.login_register.WeChatBean;
import com.avic.rong.bean.login_register.WxLoginBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.NetWorkUtils;
import com.avic.rong.utils.RegexUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.dialog.CustomDialog;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import io.reactivex.disposables.Disposable;

//登录
public class LoginActivity extends RxAppCompatActivity implements   BGASwipeBackHelper.Delegate{
    private static final int REFRESH = 200;
    public static String ARG_URL = "arg_url";
    public static final String ARG_COME = "come_from";
    private static final int LOGIN_TYPE_ACCOUNT = 1;
    private static final int LOGIN_TYPE_PHONE = 2;
    @BindView(R.id.btn_login)
    Button btn_login;


    private Context mContext;
    private int currentLoginType = LOGIN_TYPE_ACCOUNT;

    @BindView(R.id.view_left)
    View view_left;// 动画图片
    @BindView(R.id.view_right)
    View view_right;
    @BindView(R.id.login_pwd_group)
    LinearLayout login_pwd_group;//密码登录

    //    //密码方式
    @BindView(R.id.type_pwd_phone)
    EditText type_pwd_phone;//手机号
    @BindView(R.id.type_pwd_pwd)
    EditText type_pwd_pwd;//密码
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_register)
    TextView tv_register;
    @BindView(R.id.tv_find_pwd)
    TextView tv_find_pwd;
    @BindView(R.id.iv_wechat)
    ImageView iv_wechat;



    private static String comeFrom;


    private UserLoginApi userMobileLoginApi;
    private Disposable otherPlatFormLocalRegistDisposable = null;
    private Disposable countDownDisposable;
    public static SoftReference<LoginActivity> instance;
    private UMShareAPI mShareAPI;
    private String iconurl;
    private String uid;
    private String name;
    private String s;
    private WxLoginApi wxLoginApi;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private BGASwipeBackHelper mSwipeBackHelper;
    private InputMethodManager imm;
    private CircleProgressDialog circleProgressDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);

        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(this);

        circleProgressDialog = new CircleProgressDialog(this);

        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this,getResources().getColor(R.color.color_loginbg));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        if (getIntent() != null) {
            comeFrom = getIntent().getStringExtra(ARG_COME);
        }
        LoginActivity.instance = new SoftReference<>(this);
        ButterKnife.bind(this);
        mContext = this;
        userMobileLoginApi = new UserLoginApi(this, loginOnNexListener);

        mShareAPI = UMShareAPI.get(this);




        type_pwd_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 6) {
                    btn_login.setBackgroundResource(R.mipmap.bg_btlogin);
                    btn_login.setTextColor(getResources().getColor(R.color.white));
                    btn_login.setEnabled(true);
                }else{
                    btn_login.setBackgroundResource(R.drawable.common_main_r20_grey);
                    btn_login.setTextColor(getResources().getColor(R.color.black_text));
                    btn_login.setEnabled(false);
                }
            }
        });

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);

        /*//看是否有存储的用户
        sharePreferenceUtils = SharePreferenceUtils.getInstance(this);
        String username = sharePreferenceUtils.getAsString("username", null);
        String password = sharePreferenceUtils.getAsString("password", null);

        type_pwd_phone.setText(username);
        type_pwd_pwd.setText(password);*/

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
            if (this.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
         }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().postSticky(new HomePageEvent());
            startActivity(goMain());
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 登录逻辑
     */
    public void loginFunction() {
        String phone = type_pwd_phone.getText().toString().trim();
        String pwd = type_pwd_pwd.getText().toString().trim();
        if (currentLoginType == LOGIN_TYPE_ACCOUNT) {//账号密码登录
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(pwd)) {
                ToastTools.showPublicToast("账号或密码不能为空");
                return;
            }
            userMobileLoginApi.setArgument(phone, pwd);
            userMobileLoginApi.setCancel(false);
            userMobileLoginApi.setShowProgress(true);
            HttpManager.getInstance().doHttpDeal(userMobileLoginApi);
        }else if (currentLoginType == LOGIN_TYPE_PHONE){//手机号密码登录
            if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(pwd)) {
                ToastTools.showPublicToast("手机号和密码不能为空");
                return;
            }
            if (StringUtils.isEmpty(pwd)&&!StringUtils.isEmpty(phone)) {
                ToastTools.showPublicToast("密码不能为空");
                return;
            }
            if (StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(pwd)) {
                ToastTools.showPublicToast("手机号不能为空");
                return;
            }
            if (!RegexUtils.isMobileExact(phone)) {
                ToastTools.showPublicToast("手机号码格式不正确");
                return;
            }
            userMobileLoginApi.setArgument(phone, pwd);
            userMobileLoginApi.setCancel(false);
            userMobileLoginApi.setShowProgress(true);
            HttpManager.getInstance().doHttpDeal(userMobileLoginApi);
        }

    }


    @OnClick({R.id.btn_login, R.id.rl_register, R.id.img_return, R.id.rl_phone, R.id.tv_find_pwd, R.id.iv_wechat, R.id.tv_user_protocol})
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.tv_user_protocol:
                startActivity(UserProtocolActivity.queryIntent(LoginActivity.this));
                break;
            case R.id.img_return:
                if (!StringUtil.isEmpty(comeFrom)) {
                    if (comeFrom.equals("MinePageEvent")||comeFrom.equals("CartListReloadEvent")) {
                        EventBus.getDefault().postSticky(new HomePageEvent());
                        startActivity(goMain());
                    }else {
                        finish();
                    }
                }else {
                    EventBus.getDefault().postSticky(new HomePageEvent());
                    startActivity(goMain());
                }
                break;
            case R.id.btn_login://登录
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                loginFunction();
                break;
            case R.id.rl_phone://手机账号登录
                startActivity(LoginPhoneActivity.queryIntent(mContext));
                finish();
                break;
            case R.id.iv_wechat://微信登录
                login_wx();
                break;
            case R.id.rl_register://账号注册
                startActivity(RegisterActivity.getIntent(mContext,comeFrom));
                finish();
                break;
            case R.id.tv_find_pwd://找回密码
                startActivity(FindPwdActivity.queryIntent(mContext));
                break;
        }
    }
    private void login_wx() {
       /* if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP,
                    Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS,
                    Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }*/

        //切换用户就会去获取用户信息,每一次授权都会获取用户信息
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI.get(this).setShareConfig(config);

       // boolean isauth = mShareAPI.isAuthorize(this, SHARE_MEDIA.WEIXIN);

        mShareAPI.doOauthVerify(this, SHARE_MEDIA.WEIXIN, authListener);
    }


    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
           circleProgressDialog.show();
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
           circleProgressDialog.dismiss();
            //获取信息
            mShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            circleProgressDialog.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            circleProgressDialog.dismiss();
        }
    };

    UMAuthListener umAuthListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
           // ToastTools.showPublicToast("授权开始了");
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            ToastTools.showPublicToast("授权成功");


            iconurl = data.get("iconurl");
            uid = data.get("uid");
            name = data.get("name");
            String sex = data.get("gender");
            String city = data.get("city");
            String openid = data.get("openid");
            String province = data.get("province");
            String languzge = data.get("languzge");
            String country = data.get("country");

            WeChatBean weChatBean = new WeChatBean(openid, name, 1, languzge, city, province, country, iconurl,new ArrayList<>(),uid);
            Gson gson = new Gson();
            s = gson.toJson(weChatBean);


            Log.e("wcx", "iconurl: " + iconurl + "     uid: " + uid + "    " + "name: " + name);

            wxLoginApi = new WxLoginApi(LoginActivity.this, wxLoginListener);
            wxLoginApi.setArgment(uid);
            wxLoginApi.setShowProgress(true);
            wxLoginApi.setCancel(false);
            HttpManager.getInstance().doHttpDeal(wxLoginApi);

        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            ToastTools.showPublicToast("失败");
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
           // ToastTools.showPublicToast("取消了");
        }
    };

//    微信登陆
        HttpOnNextListener<BaseResultEntity> wxLoginListener = new HttpOnNextListener<BaseResultEntity>() {
            @Override
            public void onNext(BaseResultEntity baseResultEntity) {
                if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                    LoginPhoneBean data = (LoginPhoneBean) baseResultEntity.getData();
                    sharedPreferencesUtil.setLoginState(true);//登录状态
                    sharedPreferencesUtil.setLogintoken(data.getToken());
                    sharedPreferencesUtil.setUserId(data.getUserId()+"");
                    sharedPreferencesUtil.setLogintoken(data.getToken());
                    String upinter = sharedPreferencesUtil.getAsString("upinter", null);
                    Intent intent = new Intent("android.intent.action.CART_BROADCAST");
                    intent.putExtra("data", "refresh");
                    LocalBroadcastManager.getInstance(LoginActivity.this).sendBroadcast(intent);
                    sendBroadcast(intent);
                    if (!StringUtil.isEmpty(upinter)) {
                        updateInter(data.getToken(), upinter);
                    }
                    if (data.isBindingMobile()) {
                        if (!StringUtil.isEmpty(comeFrom)){
                            if (comeFrom.equals("MinePageEvent")){
                                EventBus.getDefault().postSticky(new MinePageEvent());
                                startActivity(goMain());
                            }else if (comeFrom.equals("CartListReloadEvent")){
                                EventBus.getDefault().postSticky(new CartListReloadEvent());
                                startActivity(goMain());
                            }else if (comeFrom.equals("OnlineCServiceActivity")) {
                                startActivity(OnlineCServiceActivity.getIntent(LoginActivity.this, ""));
                                finish();
                            }else {
                                finish();
                            }
                        }else {
                            finish();
                        }
                    } else {
                        showDialog();
                    }
                } else if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_BIND_PHONE_1013)) {
                    Intent intent = WxLoginActivity.queryIntent(LoginActivity.this, s);
                    intent.putExtra("wxBean",new WxLoginBean(iconurl, uid, name));
                    startActivity(intent);
                }else {
                    ToastTools.showPublicToast(baseResultEntity.getMsg());
                }
            }
    @Override
    public void onError(Throwable e) {
        String networkState = NetWorkUtils.getNetworkState(LoginActivity.this);
        ToastTools.showPublicToast(networkState);
    }
    };

    private void updateInter(String token,String sb) {
        UpdateInterestApi updateInterApi = new UpdateInterestApi(this,updateInterListener );
        updateInterApi.setArgument(token,sb);
        HttpManager.getInstance().doHttpDeal(updateInterApi);
    }

    HttpOnNextListener<BaseResultEntity> updateInterListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
//            String data = (String) baseResultEntity.getData();
//            if (data.equals("CODE_SUCCESS")){
//               ToastTools.showPublicToast("第一次更新成功");
//            }
        }
    };


    //密码登录
    private HttpOnNextListener loginOnNexListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            LoginPhoneBean data = (LoginPhoneBean) baseResultEntity.getData();
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {//成功
                sharedPreferencesUtil.setLoginState(true);//登录状态
                sharedPreferencesUtil.setLogintoken(data.getToken());
                sharedPreferencesUtil.setUserId(data.getUserId()+"");
                String upinter = sharedPreferencesUtil.getAsString("upinter", null);
                if (!StringUtil.isEmpty(upinter)) {
                    updateInter(data.getToken(), upinter);
                }
                boolean bindingMobile = data.isBindingMobile();
                Log.e("wcx", "onNext:decode------- " + data.getToken() + "      bindingMobile--------" + bindingMobile);
                Intent intent = new Intent("android.intent.action.CART_BROADCAST");
                intent.putExtra("data", "refresh");
                LocalBroadcastManager.getInstance(LoginActivity.this).sendBroadcast(intent);
                sendBroadcast(intent);
                if (bindingMobile) {
                    if (!StringUtil.isEmpty(comeFrom)){
                        if (comeFrom.equals("MinePageEvent")){
                            EventBus.getDefault().postSticky(new MinePageEvent());
                            startActivity(goMain());
                        }else if (comeFrom.equals("CartListReloadEvent")){
                            EventBus.getDefault().postSticky(new CartListReloadEvent());
                            startActivity(goMain());
                        }else if (comeFrom.equals("OnlineCServiceActivity")) {
                            startActivity(OnlineCServiceActivity.getIntent(LoginActivity.this, ""));
                            finish();
                        }else {
                           finish();
                        }
                    }else {
                        finish();
                    }
                } else {
                    showDialog();
                }
            }else if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_BIND_PHONE_1013)) {
                EventBus.getDefault().postSticky(new WxLoginBean(iconurl, uid, name));
                startActivity(WxLoginActivity.queryIntent(LoginActivity.this, s));
            }else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };

    private void showDialog() {
        CustomDialog customDialog = new CustomDialog(this, R.layout.bindphone_dialog);
        customDialog.show();
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);

        customDialog.findViewById(R.id.tv_bind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BindPhoneActivity.queryIntent(LoginActivity.this));


            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownDisposable != null && (!countDownDisposable.isDisposed())) {
            countDownDisposable.dispose();
        }
        if (otherPlatFormLocalRegistDisposable != null && (!otherPlatFormLocalRegistDisposable.isDisposed())) {
            otherPlatFormLocalRegistDisposable.dispose();
        }
        EventBus.getDefault().removeAllStickyEvents();
    }



    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }


    public static Intent queryIntent(Context context, String url) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(ARG_URL, url);
        return intent;
    }


    public static Intent getIntent(Context context, String comeFrom) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(ARG_COME, comeFrom);
        return intent;
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        return intent;
    }

    public Intent goMain(){
        Intent intent = MainActivity.queryIntent(this);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return intent;
    }


}
